<template>
  <div>
    <el-form ref="passwordForm" label-position="top" :rules="passwordRules" :model="passwordForm" size="small">
      <el-form-item label="原密码：" prop="password">
        <el-input v-model="user.password" show-password />
      </el-form-item>
      <el-form-item label="新密码：" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" show-password />
      </el-form-item>
      <el-form-item label="确认新密码：" prop="confirmNewPassword">
        <el-input v-model="passwordForm.confirmNewPassword" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePassword('passwordForm')">更 改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: 'RPassword',
  props:['user'],

  data() {
    let checkAddPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      passwordForm: {
        newPassword: '',
        confirmNewPassword: ''
      },
      passwordRules:{
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ],
        confirmNewPassword:[
          {required:true ,validator:checkAddPassword, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    updatePassword(passwordForm) {
      let jwtToken = localStorage.getItem('jwtToken');
      this.$refs[passwordForm].validate((valid)=>{
        if(valid){
          axios.get('/api/users/updatePassword',
            {params:{password:this.passwordForm.newPassword},headers:{jwtToken:jwtToken}
            }).then(result=>{
            if(result.data.code === 200){
              if(result.data.data>0){
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success',
                  duration: 2000
                });
              }
              this.passwordForm = {};
              this.$refs[passwordForm].clearValidate();
            }else {
              this.$message({
                showClose: true,
                message: '修改失败！',
                type: 'warning',
                duration:2000
              });
            }
          }).catch(e=>{
            this.$message({
              showClose: true,
              message: '服务器去火星了!',
              type: 'warning',
              duration:2000
            });
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
